/**
 * Created by Administrator on 2017/4/1.
 */
import React, {Component} from 'react';
import {
    AppRegistry,
    StyleSheet,
    Text,
    Image,
    View,
    ScrollView
} from 'react-native';

var JsonData = require('./test2.json');
var Dimensions = require('Dimensions');
var ScreenWidth = Dimensions.get('window').width;
class BannerView extends Component {
    constructor(props){
        super(props);
        this.state={
            currentPage:0,
        }
    }

    renderchilds = ()=> {
        return JsonData.data.map((item, i)=> {
            return <Image key={`item${i}`} style={styles.imageStyle} source={{uri:item.url}}></Image>
        });

    };

    handleScroll= (e)=> {
        var x = e.nativeEvent.contentOffset.x;
        var pageIndex = Math.floor(x / ScreenWidth);
        console.log(pageIndex);
        this.setState({currentPage: pageIndex});
    }

    renderCircles = ()=> {
        return JsonData.data.map((item, i)=> {
            var style ={};
            if (i === this.state.currentPage){
                style = {color:'orange'};
            }
            return <Text key={`text${i}`}  style={[styles.circleStyle,style]}>&bull;</Text>
        });
    };


    startTimer=()=>{
      this.timer =   setInterval(()=>{
            var pageIndex = ++this.state.currentPage ==JsonData.data.length?0:this.state.currentPage;
            this.setState({state:pageIndex});
            var offsetX = pageIndex*ScreenWidth;
            this.refs.scrollView.scrollTo({x:offsetX, y:0,animated:true});
        },2000)
    }
    render() {
        return <View style={styles.container}>
            <ScrollView horizontal={true}
                        pagingEnabled={true}
            onScroll={this.handleScroll}
            ref="scrollView"
            onScrollBeginDrag={this.handleScrollBeginDrag}
            onScrollEndDrag={this.handleScrollEndDrag}>
                {this.renderchilds()}
            </ScrollView>
        <View style={styles.cicleWrapperStyle}>
            {this.renderCircles()}
        </View>
        </View>

    }


    componentDidMount=()=>{
        this.startTimer();
    }



    componentWillUnmount=()=>{
        clearInterval(this.timer);

    }

    handleScrollBeginDrag=()=>{
        clearInterval(this.timer);
    }

    handleScrollEndDrag=()=>{
        this.startTimer();

    }

}

var styles = StyleSheet.create({
    container: {
        flexDirection: 'column'
    },
    imageStyle: {
        width: ScreenWidth,
        height: ScreenWidth,
    },
    circleStyle:{
        fontSize:25,
        color:"#2ff"
    },
    cicleWrapperStyle:{
        flexDirection:'row',
        position:'absolute',
        bottom:0,
        left:30

    }
});
module.exports = BannerView;